package com.server.aspect;

import com.alibaba.fastjson.JSON;
import com.server.exception.OperationFailException;
import com.server.component.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName NoRepeatSubmitAop
 * @Description TODO
 * @Author
 * @Date 2020/4/26 16:47
 */
@Slf4j
@Component
@Aspect
@Order(99)
public class NoRepeatSubmitAop {

    private static final String JWT_TOKEN_KEY = "_token";

    @Resource
    private RedisUtil redisUtil;

    @Pointcut("@annotation(com.server.annotation.NoRepeatSubmit)")
    public void controllerNoRepeat(){}

    @Around("controllerNoRepeat()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        HttpServletRequest request =
                ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest();
        String jwtToken = request.getHeader(JWT_TOKEN_KEY);
        String key = jwtToken + "-" + request.getServletPath() + JSON.toJSONString(request.getParameterMap());

        if(null == (String)redisUtil.get(key)){
            Object o = pjp.proceed();
            redisUtil.set(key,"0",1);
            return o;
        }else {
            log.error("重复提交");
            throw new OperationFailException("重复提交");
        }
    }
}
